<?php

defined( '_JEXEC' ) or die( 'Restricted access' );
require_once( JApplicationHelper::getPath( 'admin_html' ));
require_once( JApplicationHelper::getPath( 'toolbar_html' ));
JTable::addIncludePath(JPATH_COMPONENT.DS.'tables');
switch($task)
{
	case 'edit' :
	case 'add' :
		editTransport( $option );
		break;
	
	case 'apply' :
	case 'save' :
		saveTransport( $option, $task );
		break;
	
	case 'remove' :
		removeTransport( $option );
		break;
		
	case 'updateJarak' :
		updateJarak ($option);
		break;
		
	case 'updateJalur' :
		updateJalur ($option);
		break;
		
	case 'updateJarakSama' :
		updateJarakSama ($option);
		break;
		
	case 'updateSama' :
		updateSama ($option);
		break;
	
	default :
		showTransport( $option );
		break;
}

function editTransport( $option )
{
	$row =& JTable::getInstance('transport', 'Table');
	$cid = JRequest::getVar( 'cid', array(0), '', 'array');
	$id = $cid[0];
	$row->load($id);	
	$lists = array();
	$lists['status'] = JHTML::_('select.booleanlist', 'status','class="inputbox"', $row->status);	
	HTML_transports::editTransports($row, $lists, $option);
}

function saveTransport($option, $task)
{
	// buat upload
	// Configuration - Your Options
	$allowed_filetypes = array('.kml'); 
	$max_filesize = 524288; 
	$upload_path = '/home3/nusantar/public_html/PETA/jalur/';
 
	$filename = $_FILES['userfile']['name'];
	$path = $upload_path.''.$filename;
	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
	if(!in_array($ext,$allowed_filetypes))
		die('The file you attempted to upload is not allowed.');
 
	if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
		die('The file you attempted to upload is too large.');
 
	if(!is_writable($upload_path))
		die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
	if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
		echo 'Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>';
	else
		echo 'There was an error during the file upload.  Please try again.'; 

	global $mainframe;
	$row =& JTable::getInstance('transport', 'Table');
	if(!$row->bind(JRequest::get('post')))
	{
		echo "<script>alert('".$row->getError()."'); 
		window.history.go(-1);</script>\n";
		exit();
	}
	
	$row->path_file = $path;
	$row->nama_file = $filename;
	
	if(!$row->store())
	{
		echo "<script>alert('".$row->getError()."'); 
		window.history.go(-1);</script>\n";
		exit();
	}
	
	 switch ($task)
	{
		case 'apply':
			$msg = 'Changes to Review saved';
			$link = 'index.php?option=' . $option . '&task=edit&cid[]='. $row->id;
			break;
		case 'save':
		default:
			$msg = 'Review Saved';
			$link = 'index.php?option=' . $option;
		break;
	}
	$mainframe->redirect($link, $msg);
}

function showTransport( $option )
{
	$db =& JFactory::getDBO();
	$query = 'select * from transport';
	$db->setQuery($query);
	$rows = $db->loadObjectList();
	if($db->getErrorNum())
	{
		echo $db->stderr();
		return false;
	}
	HTML_transports::showTransports($option, $rows);
}

function removeTransport( $option )
{
  global $mainframe;
  $cid = JRequest::getVar( 'cid', array(), '', 'array' );
  $db =& JFactory::getDBO();
  if(count($cid))
  {
    $cids = implode( ',', $cid );
    $query = "DELETE FROM transport WHERE id IN ( $cids )";
    $db->setQuery( $query );
    if (!$db->query()) 
    {
      echo "<script> alert('".$db->getErrorMsg()."'); 
      window.history.go(-1); </script>\n";
    }
  }
  $mainframe->redirect( 'index.php?option=' . $option );
}

function updateJalur ($option)
{
	global $mainframe;
	$querys = "truncate table jalur";
$adds = mysql_query($querys);
$results = mysql_query("SELECT count(*) FROM `transport`");
$rows = mysql_fetch_row($results);
$nos = $rows[0];

for ($i = 1; $i <= $nos; $i++) {
$result = mysql_query("SELECT Nama_file FROM `transport` where id =$i");
$row = mysql_fetch_row($result);
$jalur = $row[0];


$xml = simplexml_load_file("jalur/".$jalur);
echo $xml;
$stop = "0";
$cek = 1;
$status = 1;



foreach($xml->children() as $child)
  {
		foreach($child->children() as $child2)
		{
			foreach($child2->children() as $child3)
			{
					foreach($child3->children() as $child4)
					{
						if ($child4->getName() == coordinates && $stop == "0"){
							$stop = "1";
							$tok = strtok($child4, " \n\t");
							while ($tok !== false) {
								$tok2 = strtok($child4, ",");
								while ($tok2 !== false) {
									if($tok2 !== "0") {
										//echo "$tok2<br />";
										if ($status == 1) { 
										$pos = 1;
										} else {
										$resultis = mysql_query("select status from transport where id = $i");
										$rowis = mysql_fetch_row($resultis);
										$titiks = $rowis[0];
										
											if ($titiks == 1){
											$pos = 0;
											}else{
											$pos = 0;
											}
										}
										if ($cek == 1) {
										$query = "INSERT INTO jalur (idt, lng, status, cek) VALUES ($i, $tok2, $pos,1)";
										$add = mysql_query($query);
										$cek = $cek+1;
										$status = $status+1;
										} else {
										$query = "update jalur set lat = $tok2, cek = 0 where cek = 1";
										$cek = $cek-1;
										$add = mysql_query($query);
										}
									}
									$tok2 = strtok(" ,\n\t");
								}
								$tok = strtok(" \n\t");
							}
						}
					}
			}
		}
  }
  $resultis = mysql_query("select max(id) as id from jalur");
$rowis = mysql_fetch_row($resultis);
$titik = $rowis[0];
$queries = "update jalur set status = 1 where id = $titik";
$addis = mysql_query($queries);
  
  }
   $mainframe->redirect( 'index.php?option=' . $option );
}

function updateJarak ($option)
{
	$querys = "truncate table jarak";
$adds = mysql_query($querys);
$querysi = "truncate table simpul";
$adds = mysql_query($querysi);
$x =1;
$results = mysql_query("SELECT count(*) FROM `transport`");
$rows = mysql_fetch_row($results);
$nos = $rows[0];

for ($i = 1; $i <= $nos; $i++) {
	//echo $i ."<br>";
	$result = mysql_query("SELECT count(*) FROM `jalur` where idt =$i");
	$row = mysql_fetch_row($result);
	$no = $row[0];
//echo $no."<br>";
	for ($j = 1; $j < $no; $j++) {
	$result1 = mysql_query("SELECT id,lat,lng FROM `jalur`where id =$x");
	$row1 = mysql_fetch_row($result1);
	$id1 = $row1[0];
	$lat1 = $row1[1];
	$lng1 = $row1[2];
	
	$x = $x+1;
	//echo $x;
	$result2 = mysql_query("SELECT id, lat, lng FROM `jalur`where id =$x");
	$row2 = mysql_fetch_row($result2);
	$id2 = $row2[0];
	$lat2 = $row2[1];
	$lng2 = $row2[2];
	//echo $id2."=".$lat2."dan".$lng2."<br>";
	
	$longitude1 = $lng1;
	$longitude2 = $lng2;
	$latitude1 = $lat1;
	$latitude2 = $lat2;
	$unit = 'Mi';

	$theta = $longitude1 - $longitude2;
	$distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) +
	(cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) *
	cos(deg2rad($theta)));
	$distance = acos($distance);
	$distance = rad2deg($distance);
	$distance = $distance * 60 * 1.1515;
	$distances = $distance * 1609.344;

	//echo $id1."dan".$id2."=".$distance."<br>";
	$sql= "INSERT INTO jarak (id1, id2, jarak) VALUES ($id1, $id2, $distances)";
	$add = mysql_query($sql);
	}
	$resultes = mysql_query("select sum(jarak) as jarak from jarak inner join jalur on jarak.id1 = jalur.id where jalur.idt = $i");
	$rowes = mysql_fetch_row($resultes);
	$noes = $rowes[0];
	
	$resul = mysql_query("SELECT max(id) as max, min(id) as min FROM `jalur` WHERE idt = $i");
	$ro = mysql_fetch_row($resul);
	$max = $ro[0];
	$min = $ro[1];
	
	//echo $noes."-".$min."-".$max."<br>";
	$sqls= "INSERT INTO simpul (id1, id2, jarak) VALUES ($min, $max, $noes)";
	$add = mysql_query($sqls);
	
	$x++;
}
}

function updateJarakSama ($option)
{
$result = mysql_query("SELECT * FROM `sama`");

$results = mysql_query("SELECT count(id) FROM `simpul`");
$rowe = mysql_fetch_row($results);
$i = $rowe[0];


while ($row = mysql_fetch_object($result)) {
	
    $idd = $row->id1;
	$idt = $row->id2;
//	echo $idd."-".$idt."<br>";
	
	$result1 = mysql_query("SELECT * FROM `simpul` where id1 = $idd && id <= $i");
	while ($row = mysql_fetch_object($result1)) {
	$jarak1 = $row->jarak;
	$id2 = $row->id2;
	$query1 = "INSERT INTO simpul (id1, id2, jarak) VALUES ($idt, $id2, $jarak1)";
	$add = mysql_query($query1);
	//echo $idt."-".$id2."-".$jarak1."<br>";

	}

	$result2 = mysql_query("SELECT * FROM `simpul` where id2 = $idd && id <= $i");
	while ($row = mysql_fetch_object($result2)) {
	$jarak2 = $row->jarak;
	$id1 = $row->id1;
	$query2 = "INSERT INTO simpul (id1, id2, jarak) VALUES ($id1, $idt, $jarak2)";
	$add = mysql_query($query2);
	//echo $id1."-".$idt."-".$jarak2."<br>";

	}

	$result3 = mysql_query("SELECT * FROM `simpul` where id2 = $idt && id <= $i");
	while ($row = mysql_fetch_object($result3)) {
	$jarak3 = $row->jarak;
	$id1 = $row->id1;
	$query3 = "INSERT INTO simpul (id1, id2, jarak) VALUES ($id1, $idd, $jarak3)";
	$add = mysql_query($query3);
	//echo $id1."-".$idd."-".$jarak3."<br>";

	}

	$result4 = mysql_query("SELECT * FROM `simpul` where id1 = $idt && id <= $i");
	while ($row = mysql_fetch_object($result4)) {
	$jarak4 = $row->jarak;
	$id2 = $row->id2;
	$query4 = "INSERT INTO simpul (id1, id2, jarak) VALUES ($idd, $id2, $jarak4)";
	$add = mysql_query($query4);
	//echo $idd."-".$id2."-".$jarak4."<br>";

	}

}
}

function updateSama ($option)
{
$querys = "truncate table sama";
$adds = mysql_query($querys);
$result = mysql_query("SELECT count(*) FROM `jalur`");
$row = mysql_fetch_row($result);
$jumlah = $row[0];

for ($i=1; $i <= $jumlah; $i++){
		for ($j=$i+1; $j <= $jumlah; $j++){

		//echo $i." dan ".$j."<br>";
				$awal = mysql_query("SELECT id, lat, lng, status FROM `jalur` where id = $i");
				$awal = mysql_fetch_row($awal);
				$id1 = $awal[0];
				$lat1 = $awal[1];
				$lng1 = $awal[2];
				$status1 = $awal[3];

				$akhir = mysql_query("SELECT id, lat, lng, status  FROM `jalur` where id = $j");
				$akhir = mysql_fetch_row($akhir);
				$id2 = $akhir[0];
				$lat2 = $akhir[1];
				$lng2 = $akhir[2];
				$status2 = $awal[3];

	
					if ($lat1 === $lat2 && $lng1 === $lng2 && $status1 == 1 && $status2 == 1){
					$query = "INSERT INTO sama (id1, id2) VALUES ($id1, $id2)";
					$add = mysql_query($query);
				}
			}	
		}

  
}

?>